package com.takeaway.service.serviceimpl;

import com.takeaway.const_.Const;
import com.takeaway.dao.daointerface.CouponDao;
import com.takeaway.dao.daointerface.FoodDao;
import com.takeaway.dao.daointerface.SentCouponDao;
import com.takeaway.dao.daointerface.ShopDao;
import com.takeaway.dao.daolmpl.CouponDaoImpl;
import com.takeaway.dao.daolmpl.FoodDaoImpl;
import com.takeaway.dao.daolmpl.SentCouponImpl;
import com.takeaway.dao.daolmpl.ShopDaoImpl;
import com.takeaway.pojo.Coupon;
import com.takeaway.pojo.Food;
import com.takeaway.pojo.SentCoupon;
import com.takeaway.pojo.Shop;
import com.takeaway.service.serviceinterface.CouponService;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 后台赖骏
 */
public class CouponServiceImpl implements CouponService {
    private static final CouponDao COUPON_DAO = new CouponDaoImpl();
    private static final SentCouponDao SENT_COUPON_DAO = new SentCouponImpl();
    private static final ShopDao SHOP_DAO = new ShopDaoImpl();
    private static final FoodDao FOOD_DAO = new FoodDaoImpl();
    @Override
    public Object[] checkCoupon(int userId) throws Exception {
        String[] checkField = {Const.FIELD_USERID};
        ArrayList<Coupon> coupons = COUPON_DAO.selectMore(Coupon.class, checkField, userId);
        List<Shop> shops = new ArrayList<>();
        for (Coupon coupon: coupons) {
            String[] checkField1 = {Const.FIELD_ID};
            Shop shop = SHOP_DAO.selectSingle(new Shop(), checkField1, coupon.getShopId());
            shops.add(shop);
        }
        Object[] objects = new Object[2];
        objects[0] = coupons;
        objects[1] = shops;
        return objects;
    }
    @Override
    public List<Coupon> checkShopCoupon(int userId,int foodId) throws Exception {
        String[] checkField = {Const.FIELD_ID};
        Food food = FOOD_DAO.selectSingle(new Food(), checkField, foodId);
        String[] checkField1 = {Const.FIELD_USERID,Const.FIELD_SHOP_ID};
        return COUPON_DAO.selectMore(Coupon.class, checkField1, userId,food.getShopId());
    }

    @Override
    public int deleteCoupon(int couponId) throws Exception {
        String[] checkField = {Const.FIELD_ID};
        return COUPON_DAO.delete(Coupon.class,checkField,couponId);
    }

    @Override
    public int addCoupon(int shopId, int userId) throws Exception {
        Timestamp expirationTime = new Timestamp(System.currentTimeMillis()+60*1000);
        String[] checkField = {Const.FIELD_SHOP_ID};
        SentCoupon sentCoupon = SENT_COUPON_DAO.selectSingle(new SentCoupon(), checkField, shopId);
        if (sentCoupon.getIsSent()==1){
            return 0;
        }
        return COUPON_DAO.insert(new Coupon(shopId,userId,expirationTime));
    }
}
